'use strict';
const db = uniCloud.database();

/**
 * 云函数：学生签到
 * @param {Object} event - 请求参数
 * @param {string} event.user_id - 用户ID
 * @returns {Object} - 签到结果
 */
exports.main = async (event, context) => {
  const { user_id } = event;
  try {
    const userCollection = db.collection('users');
    const checkinCollection = db.collection('checkins');
    const now = new Date();
    const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
    const todayEnd = todayStart + 24 * 60 * 60 * 1000 - 1;

    // 检查是否已签到
    const checkinRes = await checkinCollection
      .where({
        user_id,
        checkin_date: db.command.gte(todayStart).lte(todayEnd)
      })
      .count();

    if (checkinRes.total > 0) {
      return { code: -1, msg: '今日已签到' };
    }

    // 获取用户信息
    const userRes = await userCollection.doc(user_id).get();
    const user = userRes.data[0];
    if (!user) {
      return { code: -1, msg: '用户不存在' };
    }

    // 计算连续签到天数
    const yesterdayStart = todayStart - 24 * 60 * 60 * 1000;
    const yesterdayEnd = todayStart - 1;
    const yesterdayCheckin = await checkinCollection
      .where({
        user_id,
        checkin_date: db.command.gte(yesterdayStart).lte(yesterdayEnd)
      })
      .count();

    const consecutiveDays = yesterdayCheckin.total > 0 ? (user.consecutive_days || 0) + 1 : 1;
    const earnedPoints = consecutiveDays >= 5 ? 10 : 5;

    // 更新用户数据
    const newPoints = (user.points || 0) + earnedPoints;
    await userCollection.doc(user_id).update({
      points: newPoints,
      consecutive_days: consecutiveDays,
      last_checkin: Date.now(),
      updated_at: Date.now()
    });

    // 添加签到记录
    await checkinCollection.add({
      user_id,
      checkin_date: Date.now(),
      consecutive_days: consecutiveDays,
      points_earned: earnedPoints
    });

    return {
      code: 0,
      data: {
        points: newPoints,
        earnedPoints,
        consecutiveDays
      },
      msg: '签到成功'
    };
  } catch (e) {
    console.error('签到失败:', e);
    return { code: -1, msg: '签到失败' };
  }
};